package com.example.wheresmystuff2;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;


/**
 * This is the Filter Page Activity that allows us to filter our items
 * @author Team 26
 */
public class FilterPage extends Activity{
	
	private Pattern pattern = Pattern.compile("(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d)");
	private Matcher matcher;
	Database db;
	
	/**
	 * Method that is called when activity is created and sets up the global state
	 * @param savedInstanceState the last state saved on last running this app (saved by onSaveInstanceState(
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_filter_page);
		db = new Database(this);
		
		//create button instance and save the 'Add' button's id in it
		Button doneButton = (Button) findViewById(R.id.filter_page_done);
		Button cancelButton = (Button) findViewById(R.id.filter_page_cancel);
		
		//Create radio groups
		final RadioGroup rg1 = (RadioGroup)findViewById(R.id.open_or_closed_radio_group);
		final RadioGroup rg2 = (RadioGroup)findViewById(R.id.filter_category_radio_group);
		
		//Create editText field
		final EditText dateText= (EditText) findViewById(R.id.filter_page_found_after);
		
		//error field to be updated if error
		final TextView error= (TextView) findViewById(R.id.filter_page_errorField);
		
		//add button listener to 'Done' button
		doneButton.setOnClickListener(new OnClickListener()
	    {
			/**
			 * Method that sends data from buttons and text fields to Gallery when 'Done' button is pressed
			 * @param v the view being pressed ('Done' button)
			 */
			public void onClick(View v) {
				//radio buttons that were selected when button pressed
				db.open();
				final RadioButton openOrClosedButton = (RadioButton) findViewById(rg1.getCheckedRadioButtonId());
				final RadioButton categoryButton = (RadioButton) findViewById(rg2.getCheckedRadioButtonId());
				
				//instantiate strings for adding to gallery
				String status = openOrClosedButton.getText().toString(); //lost or found
				String category = categoryButton.getText().toString();//Keepsake, Heirloom, or Misc.
				String enterDate=dateText.getText().toString();
				if(validate(enterDate)){
					
					String[] dateNums=enterDate.split("/");
					//surrounded with try/catch
					Gallery.setFilteredItems(filterItems(db.getItemTableAsHashMap(), status,category,new Date(Integer.parseInt(dateNums[2])-1900,Integer.parseInt(dateNums[0]),Integer.parseInt(dateNums[1]))));

					Gallery.setFiltered(true);
				
					Intent myIntent = new Intent(FilterPage.this, Gallery.class);
					FilterPage.this.startActivity(myIntent);
				}
				else{
					error.setText("Invalid Date. Format MM/DD/YYYY");
				}
			}
	    });
		
		cancelButton.setOnClickListener(new OnClickListener()
	    {
			/**
			 * Method that sends data from buttons and text fields to Gallery when 'Cancel' button is pressed
			 * @param v the view being pressed ('Cancel' button)
			 */
			public void onClick(View v) {		
			 	Intent myIntent = new Intent(FilterPage.this, Gallery.class);
			 	FilterPage.this.startActivity(myIntent);
			}
	    });
	}
	/**
	 * Filters the items in the map parameter by the other parameters specified
	 * @param map to filter
	 * @param status to filter by
	 * @param category to filter by
	 * @param date to filter by
	 * @return filteredMap
	 */
	public static Map<String,ArrayList<Object>> filterItems(Map<String, ArrayList<Object>> map, String status, String category,Date date){	
		Map<String, ArrayList<Object>> filteredItems =new HashMap<String, ArrayList<Object> >();
		Set<String> itemList = map.keySet();
		
		for (String item:itemList) {
			String iStatus=(String) map.get(item).get(2);
			String dateStr = (String) map.get(item).get(5);
			//date conversion
			Date iDate;
			String[] dateNums=dateStr.split("/");
			//surrounded with try/catch
			iDate = new Date(Integer.parseInt(dateNums[2])-1900,Integer.parseInt(dateNums[0]),Integer.parseInt(dateNums[1]));	
			String iCategory=(String) map.get(item).get(3);
			if (status.equals("Any")||iStatus.equals(status)) {
				if(category.equals("Any")||iCategory.equals(category)){
					if(date.before(iDate)){
						filteredItems.put(item, map.get(item));
					}
				}
			}
		}
		return filteredItems;
	}
	 
	/**
	 * Validate date format with regular expression
	 * @param date date address for validation
	 * @return true valid date format, false invalid date format
	 */
	public boolean validate(final String date){
		matcher = pattern.matcher(date);
		if(matcher.matches()){
			matcher.reset();
			if(matcher.find()){
				String month = matcher.group(1);
				String day = matcher.group(2);
				int year = Integer.parseInt(matcher.group(3));
				if (day.equals("31") && (month.equals("4") || month .equals("6") || month.equals("9") || month.equals("11") || month.equals("04") || month.equals("06") || month.equals("09"))) {
					return false; // only 1,3,5,7,8,10,12 has 31 days
				}
				else if (month.equals("2") || month.equals("02")) {
					//leap year
					if(year % 4==0){
						if(day.equals("30") || day.equals("31")){
							return false;
						}
						else{
							return true;
						}
					}
					else{
						if(day.equals("29")||day.equals("30")||day.equals("31")){
							return false;
						}
						else{
							return true;
						}
					}
				}
				else{				 
					return true;				 
				}
			}
			else{
				return false;
			}		  
		}
		else{
			return false;
		}			    
	}
}
